<template>
  <div class="login-container">
    <video autoplay loop muted playsinline>
      <source src="/static/custom-login/bg.mp4" />
    </video>
    <div class="absolute bottom-0 left-0 right-0 top-0"></div>

    <Form
      class="login-form"
      ref="formRef"
      :rules="rules"
      :model="formState"
      layout="vertical"
      hideRequiredMark
    >
      <h3 v-if="title" class="title-wrap">
        {{ title }}
      </h3>
      <FormItem class="mb-6" label="" name="tenantCode">
        <Flex align="center">
          <Select
            class="custom-select"
            v-model:value="formState.tenantCode"
            :options="tenantOptions"
            placeholder="请选择租户"
          >
            <template #suffixIcon>
              <UserOutlined></UserOutlined>
            </template>
          </Select>
          <router-link class="ml-2 w-8" to="/license">授权</router-link>
        </Flex>
      </FormItem>
      <FormItem class="mb-6" label="" name="username">
        <Input
          v-model:value="formState.username"
          placeholder="账号"
          allow-clear
        >
          <template #prefix><UserOutlined></UserOutlined></template>
        </Input>
      </FormItem>
      <FormItem class="mb-4" name="password">
        <InputPassword
          v-model:value="formState.password"
          placeholder="密码"
          @keyup.enter="handleLogin"
          allow-clear
        >
          <template #prefix><LockOutlined></LockOutlined></template>
        </InputPassword>
      </FormItem>
      <FormItem name="code" v-if="needCaptcha">
        <Flex>
          <Input
            v-model:value="formState.code"
            placeholder="验证码"
            @keyup.enter="handleLogin"
          ></Input>
          <img
            class="captcha-image ml-2 h-10 rounded-sm"
            :src="captcha"
            @click="refreshCode"
          />
        </Flex>
      </FormItem>
      <FormItem class="mb-8">
        <Checkbox v-model:checked="formState.rememberMe">
          <span class="remember-password">记住密码</span>
        </Checkbox>
      </FormItem>
      <FormItem>
        <Button class="login-btn" @click="handleLogin" :loading="loading"
          >登录</Button
        >
      </FormItem>
    </Form>
  </div>
</template>

<route lang="json">
{
  "name": "custom-login",
  "meta": {
    "layout": false,
    "hideInTabs": true
  }
}
</route>

<script setup lang="ts">
import { CSSProperties, computed, onMounted, ref } from 'vue';
import { LockOutlined, UserOutlined } from '@ant-design/icons-vue';
import { useTabViewsStore, useUserStore } from '@boeyo/portal';
import {
  Button,
  Checkbox,
  Flex,
  Form,
  FormInstance,
  FormItem,
  FormProps,
  Input,
  InputPassword,
  Select,
  Space,
} from 'ant-design-vue';
import Cookie from 'js-cookie';
import { useRequest } from 'vue-request';
import { useRoute, useRouter } from 'vue-router';
import { fetchCodeImageApi, fetchTenantOptions, tenantLogin } from './api';

const route = useRoute();

const router = useRouter();

const USER_NAME_KEY = 'ACCOUNT';
const PASSWORD_KEY = 'ACCOUNT_SECRET';
const CHECK_EXPIRE_KEY = 'CHECK_EXPIRE';

interface LoginState {
  tenantCode: string;
  username: string;
  password: string;
  rememberMe: boolean;
  code: string;
  uuid: string;
}

const formRef = ref<FormInstance>();
const formState = ref<LoginState>({
  tenantCode: undefined,
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: '',
});

const checkExpire = ref('');

const rules: FormProps['rules'] = {
  // tenantCode: [{ trigger: 'blur', required: true, message: '请选择租户' }],
  username: [{ trigger: 'blur', required: true, message: '请输入用户名' }],
  password: [{ trigger: 'blur', required: true, message: '请输入密码' }],
  code: [{ trigger: 'blur', required: true, message: '请输入验证码' }],
};

const title = '地震预警工程应用平台';

const tenantOptions = ref([]);

const tabViewsStore = useTabViewsStore();

onMounted(() => {
  tabViewsStore.closeAllTab();
  const username = Cookie.get(USER_NAME_KEY);
  const password = Cookie.get(PASSWORD_KEY);
  checkExpire.value = Cookie.get(CHECK_EXPIRE_KEY) || true;
  if (username && password) {
    formState.value = {
      ...formState.value,
      username,
      password: atob(password),
      rememberMe: true,
    };
  }

  fetchTenantOptions().then((res) => {
    if (!res.data?.length) {
      router.push('/license');
      return;
    }
    tenantOptions.value = res.data;
    formState.value.tenantCode = res.data?.[0].value;
  });
});

const { run: login, loading } = useRequest(tenantLogin, {
  manual: true,
  onSuccess(result) {
    if (result.token) {
      useUserStore().setToken(result.token);
    }
    if (result.expire) {
      router.push({
        path: '/license',
        state: {
          msg: result.msg,
          expire: true,
        },
      });
      return;
    }
    router.push({ path: (route.query.redirect as string) || '/dashboard' });
  },
});

const handleLogin = async () => {
  const result = await formRef.value?.validate();

  if (formState.value.rememberMe) {
    const { username, password } = formState.value;
    Cookie.set(USER_NAME_KEY, username);
    Cookie.set(PASSWORD_KEY, btoa(password));
  }
  if (!result) return;
  login({
    ...formState.value,
    checkExpire: checkExpire.value,
  });
};

const needCaptcha = ref(false);
const captcha = ref('');

const refreshCode = () => {
  fetchCodeImageApi().then((res) => {
    needCaptcha.value = (res as any).captchaEnabled ?? true;
    if (needCaptcha.value) {
      captcha.value = `data:image/gif;base64,${(res as any).img}`;
      formState.value.uuid = (res as any).uuid;
    }
  });
};

refreshCode();

const style = computed<CSSProperties>(() => {
  return {
    // backgroundImage: `url(${commonStore.loginBgUrl})`,
  };
});
</script>

<style lang="scss" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  position: relative;

  video {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.login-form {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 428px;
  padding: 42px 54px 24px;
  border-radius: 6px;
  box-shadow: 0 0 40px #08071099;
  background: url('/static/custom-login/login-form.png') no-repeat;
  background-size: 100% 100%;
}

.captcha-image {
  height: 40px;
  margin-left: 8px;
  border-radius: 2px;
}

.remember-password {
  color: #fff;
}

.login-btn {
  width: 320px;
  height: 48px;
  background: linear-gradient(180deg, #18568e 0%, #53acff 100%);
  border-radius: 6px 6px 6px 6px;
  border: none;
  color: #fff;
  font-size: 18px;
}

.title-wrap {
  color: #fff;
  font-size: 32px;
  font-weight: 600;
  text-align: center;
  margin: 0 auto 20px;
}

.custom-select {
  :deep(.ant-select-selector) {
    padding-left: 10%;
  }
  :deep(.ant-select-arrow) {
    left: 4%;
    font-size: 14px;
    // color: #333;
  }
}
</style>
